let express = require('express');
let router = express.Router();
const moment = require('moment');
const crypto = require('crypto');
const config = require('../config').wechat;
let getOpenid = require('../wechat/wechat.js');
let createUnifiedOrder = require('../wechat/createUnifiedOrder.js');
let parseXMLAsync = require('../wechat/parseXMLAsync.js');
let formatMessage = require('../wechat/formatMessage.js');
let updateOrder1 = require('../wechat/updateOrder1.js');
let getTotalMoney = require('../wechat/getTotalMoney.js');

moment.locale('zh-cn');

//支付
router.post('/',async function(req, res, next) {

    let content = req.body
    let code = content.code;// 小程序提交的 code
    let string = await getOpenid(code);//根据 code 获取 openid
    let str = JSON.parse(string)
    let openid = str.openid
    let order_sheet = content.order_sheet;// 商品订单详细
    let gettotalMoney = await getTotalMoney(order_sheet);// 获取商品价钱
    let totalMoney= gettotalMoney[0].totalMoney;

    // let ipReal = req.headers['x-forwarded-for'] ||
    //     req.connection.remoteAddress ||
    //     req.socket.remoteAddress ||
    //     req.connection.socket.remoteAddress
    // ipReal = ipReal.substring(7,40)
    let ipReal = req.ip.substring(7,40);// 当前服务器的IP地址
    // let ipReal ="127.0.0.1";
    let time_start = moment().format('YYYYMMDDHHmmss')
    let time_expire = moment().add(1, 'h').format('YYYYMMDDHHmmss')
    let out_trade_no = moment().format('YYYYMMDDHHmmss') + Math.random().toString().substr(2, 15)

    //  微信生成订单
    let wxOrder = await createUnifiedOrder(out_trade_no,'商品demo', totalMoney*100, ipReal, 'JSAPI', openid, { time_start, time_expire})//将xml传给微信
    wxOrder = await parseXMLAsync(wxOrder)//解析微信传来的xml
    wxOrder = formatMessage(wxOrder.xml)//取值

    // 生成随机数
    function createNonce () {
        return Math.random().toString(36).substr(2, 15) + Math.random().toString(36).substr(2, 15)
    }

    //签名生成函数
    function _sign (obj) {
        let params = []
        for (let key in obj) {
            let aLine = key + '=' + obj[key]
            params.push(aLine)
        }
        let strA = params.sort().join('&')
        let stringSignTemp = strA + `&key=${config.apiCert}`
        return MD5(stringSignTemp).toUpperCase()
    }
    //加密函数
    function MD5(str) {
        let md5sum = crypto.createHash('md5')
        md5sum.update(str)
        str = md5sum.digest('hex')
        return str
    }

    let prepay_id = 'prepay_id=' + wxOrder.prepay_id
    let appid = config.appID
    let nonce_str =  createNonce()
    let timeStamp = Math.ceil(Date.now() / 1000)+''
    let signType = 'MD5'
    let paySign =  _sign({ appId: appid, package: prepay_id, nonceStr: nonce_str, timeStamp, signType })//将这些信息通过签名加密
    //生成未支付的订单
    await updatePay1(order_sheet,wxOrder,out_trade_no);

    let opts = {
        appid,
        prepay_id,
        nonce_str,
        timeStamp,
        signType,
        paySign,
    };
    // 返回到客户端需要的参数
    res.json({
        status: "0",
        msg: "",
        result: {
            opts: opts
        }
    })
});


module.exports = router;